import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import {
  Card,
  Form,
  Table,
  Divider,
  Row,
  Col,
  Select,
  Button,
  Input,
  DatePicker,
  Modal,
  InputNumber,
} from 'antd';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';
import { Link } from 'dva/router';

import { getParamUrl } from '../../utils/formatDataSource';

@connect(({ role, loading }) => ({
  role,
  loading: loading.models.role,
}))
class RoleHome extends PureComponent {
  state = {
    name: '',
    job: '-1',
    campus: '-1',
    status: '1',
    users: [],
    confirmVisible: false,
    currentModal: {
      title: '该账号冻结失败',
      content: '服务器错误',
      type: 1,
    },
  };
  componentDidMount() {
    const { dispatch } = this.props;

    dispatch({
      type: 'role/personList',
    }).then(() => {
      this.setState({
        users: this.props.role.users,
      });
      this.search();
    });

    dispatch({
      type: 'role/jobs',
    });

    dispatch({
      type: 'role/campus',
    });
  }

  getData = () => {
    return [
      {
        id: 1,
        key: '1',
        name: '张三',
        campus: '长宁校区',
        createTime: '2017-01-01 12:12',
        job: '教学老师',
      },
      {
        id: 2,
        key: '2',
        name: '张三',
        campus: '长宁校区',
        createTime: '2017-01-01 12:12',
        job: '教学老师',
      },
    ];
  };
  getColumns = () => {
    return [
      {
        title: 'ID',
        dataIndex: 'id',
        key: 'id',
        align: 'center',
      },
      {
        title: '姓名',
        dataIndex: 'name',
        key: 'name',
        align: 'center',
      },
      {
        title: '校区',
        key: 'campuses',
        dataIndex: 'campuses',
        align: 'center',
        render: record => {
          const show = record.map(r => r.name).join('、');
          return <span>{show}</span>;
        },
      },
      {
        title: '创建时间',
        dataIndex: 'createTime',
        key: 'createTime',
        align: 'center',
      },
      {
        title: '职位',
        dataIndex: 'roles',
        key: 'roles',
        align: 'center',
        render: record => {
          const show = record.map(r => r.name).join('、');
          return <span>{show}</span>;
        },
      },
      {
        title: '操作',
        key: 'action',
        align: 'center',
        render: record => {
          return (
            <span>
              <a
                href="javascript:;"
                onClick={() => this.showConfirmModal(record.id)}
                hidden={record.status === 2}
              >
                冻结
              </a>
              <a
                href="javascript:;"
                onClick={() => this.showHuiFuModal(record.id)}
                hidden={record.status === 1}
              >
                恢复
              </a>&nbsp;&nbsp;
              <Link to={`/personnel/person/detail?userId=${record.id}`}>查看</Link>
            </span>
          );
        },
      },
    ];
  };

  showConfirmModal = userId => {
    const { dispatch } = this.props;
    dispatch({
      type: 'role/check',
      payload: {
        userId,
      },
    }).then(() => {
      const { existLesson } = this.props.role;
      let message = {};
      if (existLesson.length !== 0) {
        message = {
          title: '该账号冻结失败',
          content:
            '当前账号为教学老师账号，目前正为任课状态。请将该账号授课班级更换老师后再进行冻结。',
          type: 1,
          userId,
        };
      } else {
        message = {
          title: '确认冻结该账号吗',
          content: '冻结后该账号将无法登陆',
          type: 2,
          userId,
        };
      }
      this.setState({
        currentModal: message,
        confirmVisible: true,
      });
    });
  };
  showHuiFuModal = userId => {
    const message = {
      title: '确认恢复该账号吗',
      content: '恢复后，该账号可以重新登录。',
      type: 3,
      userId,
    };
    this.setState({
      currentModal: message,
      confirmVisible: true,
    });
  };
  confirmOk = () => {
    const { currentModal, users } = this.state;
    const { dispatch } = this.props;
    if (currentModal.type !== 1) {
      // 冻结 or 恢复
      dispatch({
        type: 'role/update',
        payload: {
          type: currentModal.type === 2 ? 2 : 1,
          userId: currentModal.userId,
        },
      }).then(() => {
        const userId = currentModal.userId;
        const status = currentModal.type === 2 ? 2 : 1;
        users.map(u => {
          if (u.id === userId) {
            u.status = status;
          }
        });
        this.setState({
          confirmVisible: false,
          users: [...users],
        });
        this.search();
      });
    } else {
      this.setState({ confirmVisible: false });
    }
  };
  confirmCancel = () => {
    this.setState({ confirmVisible: false });
  };

  handleChange = e => {
    const name = e.target.value;
    this.setState({ name });
  };

  campusSelect = campus => {
    this.setState({ campus });
  };
  jobSelect = job => {
    this.setState({ job });
  };
  statusSelect = status => {
    this.setState({ status });
  };

  search = () => {
    const { name, job, campus, status } = this.state;
    const { users } = this.props.role;
    let filterUser = users.filter(u => u.status + '' === status);
    filterUser = filterUser.filter(u => {
      if (name !== '') {
        return u.name.indexOf(name) > -1;
      } else {
        return u;
      }
    });
    filterUser = filterUser.filter(u => {
      if (job !== '-1') {
        return u.roles.map(r => r.name).indexOf(job) > -1;
      } else {
        return u;
      }
    });
    filterUser = filterUser.filter(u => {
      if (campus !== '-1') {
        return u.campuses.map(c => c.name).indexOf(campus) > -1;
      } else {
        return u;
      }
    });

    console.log(filterUser);

    this.setState({ users: [...filterUser] });
  };

  render() {
    const { jobs, campus } = this.props.role;

    const { users } = this.state;

    const Option = Select.Option;

    return (
      <PageHeaderLayout>
        <Card bordered={false}>
          <Row align="middle">
            <Col span={3}>
              姓名：<Input
                style={{ width: '120px' }}
                value={this.state.name}
                onChange={this.handleChange}
              />
            </Col>
            <Col span={3}>
              校区：
              <Select value={this.state.campus} style={{ width: 120 }} onChange={this.campusSelect}>
                <Option value="-1">全部校区</Option>
                {campus.map((e, i) => {
                  return (
                    <Option value={e.name} key={e.id}>
                      {e.name}
                    </Option>
                  );
                })}
              </Select>
            </Col>
            <Col span={3}>
              职位：
              <Select value={this.state.job} style={{ width: 120 }} onChange={this.jobSelect}>
                <Option value="-1">全部</Option>
                {jobs.map((e, i) => {
                  return (
                    <Option value={e.name} key={e.id}>
                      {e.name}
                    </Option>
                  );
                })}
              </Select>
            </Col>
            <Col span={3}>
              状态：
              <Select value={this.state.status} onChange={this.statusSelect}>
                <Option value="1">正常</Option>
                <Option value="2">冻结</Option>
              </Select>
            </Col>
            <Col span={12}>
              <Button type="primary" onClick={this.search}>
                查询
              </Button>&nbsp;&nbsp;
              <Button type="primary">
                <Link to={`/personnel/person/detail`}>账号添加</Link>
              </Button>
            </Col>
          </Row>
        </Card>
        <Card bordered={false}>
          <Table
            dataSource={users}
            columns={this.getColumns()}
            bordered={true}
            loading={this.props.loading}
            pagination={{
              hideOnSinglePage: true,
              showTotal: () => {
                return (
                  <span>
                    共 <span style={{ color: '#1893ab' }}>{users.length}</span> 道
                  </span>
                );
              },
            }}
          />
        </Card>

        <Modal
          title={this.state.currentModal.title}
          visible={this.state.confirmVisible}
          onOk={this.confirmOk}
          onCancel={this.confirmCancel}
        >
          <p style={{ color: 'red' }}>{this.state.currentModal.content}</p>
        </Modal>
      </PageHeaderLayout>
    );
  }
}

